package com.ruoyi.yljf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.yljf.domain.*;
import com.ruoyi.yljf.domain.dto.PracticeDTO;
import com.ruoyi.yljf.domain.vo.ExamSummaryDetailVO;
import com.ruoyi.yljf.mapper.*;
import com.ruoyi.yljf.service.IExamSummaryService;
import com.ruoyi.yljf.service.IUserScoreRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author nzhiwen
 * @description 针对表【yljf_exam_summary(考试总结表)】的数据库操作Service实现
 * @createDate 2025-04-25 10:24:26
 */

@Service
public class ExamSummaryServiceImpl extends ServiceImpl<ExamSummaryMapper, ExamSummary>
        implements IExamSummaryService {


    @Autowired
    private CoursePackageServiceImpl coursePackageService;

    @Autowired
    private ExamSummaryMapper examSummaryMapper;

    @Autowired
    private UserQuestionRecordMapper userQuestionRecordMapper;

    @Autowired
    private TestPaperMapper testPaperMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ScoreTypeMapper scoreTypeMapper;

    @Autowired
    private IUserScoreRecordService userScoreRecordService;

    @Override
    public List<ExamSummaryDetailVO> getExamSummary(Long userId, Long courseId, Long packageId) {
        List<ExamSummary> examSummary = this.list(new LambdaQueryWrapper<ExamSummary>()
                .eq(ExamSummary::getCourseId, courseId)
                .eq(ExamSummary::getChapterId, packageId)
                .eq(ExamSummary::getUserId, userId));
        if (examSummary == null || examSummary.size() == 0) return new ArrayList<ExamSummaryDetailVO>();
        List<ExamSummaryDetailVO> collect = examSummary.stream().map(item -> {
            CoursePackage one = coursePackageService.getOne(new LambdaQueryWrapper<CoursePackage>()
                    .select(CoursePackage::getName, CoursePackage::getTitle)
                    .eq(CoursePackage::getId, Long.valueOf(item.getChapterId())));
            ExamSummaryDetailVO vo = new ExamSummaryDetailVO();
            if (Objects.isNull(one)) return vo;
            BeanUtil.copyProperties(item, vo);
            vo.setExamName(one.getName());
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 用户提交课程练习题
     * @param practiceDTO
     */
    @Override
    public void updateUserPractice(PracticeDTO practiceDTO) {
        Boolean isCorrect = practiceDTO.getUserOption().equals(practiceDTO.getCorrectOption());
        Long userId = SecurityUtils.getUserId();
        ExamSummary examSummary = examSummaryMapper.selectOne(new LambdaQueryWrapper<>(ExamSummary.class)
                .eq(ExamSummary::getUserId, userId)
                .eq(ExamSummary::getCourseId, practiceDTO.getCourseId())
                .eq(ExamSummary::getChapterId, practiceDTO.getPackageId()));
        if(examSummary == null) {  // 用户章节练习记录不存在
            ExamSummary examSummary1 = new ExamSummary();
            examSummary1.setExamType("章节练习");
            examSummary1.setUserId(userId);
            examSummary1.setChapterId(practiceDTO.getPackageId());
            examSummary1.setCourseId(practiceDTO.getCourseId());
            examSummary1.setTotalQuestions(practiceDTO.getTotalQuestion());
            examSummary1.setCurQuestion(practiceDTO.getCurQuestion());
            if(isCorrect) {
                examSummary1.setCorrectAnswers(1);
                examSummary1.setWrongAnswers(0);
            } else {
                examSummary1.setCorrectAnswers(0);
                examSummary1.setWrongAnswers(1);
            }
            examSummary1.setAnswered(1);
            examSummary1.setUnanswered(examSummary1.getTotalQuestions() - 1);
            long round = Math.round(examSummary1.getCorrectAnswers() * 1D / examSummary1.getTotalQuestions() * 100);
            examSummary1.setAccuracy(round + "%");
            examSummary1.setSubmittedAt(new Date());
            examSummaryMapper.insert(examSummary1);
        } else {
            examSummary.setCurQuestion(practiceDTO.getCurQuestion());
            if(isCorrect) {
                examSummary.setCorrectAnswers(examSummary.getAnswered() + 1);
            } else {
                examSummary.setWrongAnswers(examSummary.getWrongAnswers() + 1);
            }
            examSummary.setAnswered(examSummary.getAnswered() + 1);
            examSummary.setUnanswered(examSummary.getUnanswered() - 1);
            long round = Math.round(examSummary.getCorrectAnswers() * 1D / examSummary.getTotalQuestions() * 100);
            examSummary.setAccuracy(round + "%");
            examSummary.setSubmittedAt(new Date());
            examSummaryMapper.updateById(examSummary);
        }
    }

    /**
     * 提交课程考试试卷，生成考试记录
     * @param taxonId
     */
    @Override
    public void submitPaper(Long taxonId, Date totalTime) {
        Long userId = SecurityUtils.getUserId();
        List<UserQuestionRecord> records = userQuestionRecordMapper.selectList(new LambdaQueryWrapper<>(UserQuestionRecord.class)
                .eq(UserQuestionRecord::getUserId, userId)
                .eq(UserQuestionRecord::getCourseId, taxonId));
        ExamSummary examSummary = new ExamSummary();
        examSummary.setExamType("课程考试");
        examSummary.setUserId(SecurityUtils.getUserId());
        examSummary.setCourseId(taxonId);
        Long totalCount = testPaperMapper.selectCount(new LambdaQueryWrapper<>(TestPaper.class)
                .eq(TestPaper::getPaperTaxonId, taxonId));
        examSummary.setTotalQuestions(totalCount.intValue());
        examSummary.setAnswered(records.size());
        examSummary.setUnanswered(examSummary.getTotalQuestions() - examSummary.getAnswered());
        int correctCount = 0, wrongCount = 0;
        for (UserQuestionRecord userQuestionRecord: records) {
            if(userQuestionRecord.getUserOption().equals(userQuestionRecord.getCorrectOption())) {
                correctCount ++;
            } else {
                wrongCount ++;
            }
        }
        examSummary.setCorrectAnswers(correctCount);
        examSummary.setWrongAnswers(wrongCount);
        long round = Math.round(examSummary.getCorrectAnswers() * 1D / examSummary.getTotalQuestions() * 100);
        examSummary.setAccuracy(round + "%");
        examSummary.setTotalTime(totalTime);
        examSummary.setSubmittedAt(new Date());
        examSummaryMapper.insert(examSummary);

        User user = userMapper.selectById(userId);
        ScoreType scoreType = scoreTypeMapper.selectOne(new LambdaQueryWrapper<>(ScoreType.class)
                .eq(ScoreType::getType, "参加考试"));
        userScoreRecordService.adduserScore(user, scoreType);
    }
}




